from typing import List

from utils import DELIMITER, SYSTEM_DIR
from utils import parse_kwargs

service_name = "keepalived.service"


def gen_service_content(insecure_registry_list: List[str], dns_list: List[str], work_dir: str):
    insecure_registry = ["--insecure-registry={}".format(each) for each in insecure_registry_list]
    insecure_registry_args = DELIMITER.join(insecure_registry)

    dns = ["--dns={}".format(each) for each in dns_list]
    dns_args = DELIMITER.join(dns)

    work_dir_args = "-g={}".format(work_dir)

    with open("docker.service", 'r') as file:
        SERVICE = file.read()

    SERVICE = SERVICE.format(
        work_dir_args=work_dir_args,
        insecure_registry_args=insecure_registry_args,
        dns_args=dns_args
    )

    return SERVICE


def gen_install_command(source: str, application_dir: str):
    docker_package = source.split("/")[-1]

    chains = []

    chains.append("wget {}".format(source))
    chains.append("tar -xzvf {} -C {}".format(docker_package, application_dir))
    chains.append("ln -s {}/docker/* /usr/bin".format(application_dir))
    chains.append("systemctl daemon-reload")
    chains.append("systemctl enable {}".format(service_name))
    chains.append("systemctl start docker")
    chains.append("rm -rf {}".format(docker_package))

    return chains


def gen_install_document():
    kwargs = parse_kwargs("settings.json")

    service_file = gen_service_content(
        insecure_registry_list=kwargs["insecure_registry_list"],
        dns_list=kwargs["dns_list"],
        work_dir=kwargs["work_dir"]
    )
    with open("dist/docker.service", 'w') as f:
        f.write(service_file)

    cmds = gen_install_command(
        source=kwargs["source"],
        application_dir=kwargs["application_dir"]
    )
    cmds = "\n".join(cmds)

    docs = """
        请在每台需要部署docker的机器中执行下列操作

        1、编辑进程管理文件{service_path},内容参考{service_name}
        2、按顺序执行下列命令
        {cmds}
        """.format(
        service_path="{}{}".format(SYSTEM_DIR, service_name),
        service_name=service_name,
        cmds=cmds,
    )
    with open("dist/doc.txt", 'w') as f:
        f.write(docs)


if __name__ == '__main__':
    gen_docker_install_document()
